<?php

namespace app\common\model;


class SysCountries extends BaseModel
{
    protected $pk = 'country_id';

    /**
     * 通过国家编码获取一条数据
     * @param string $code 国家二字简码或者三字简码
     * @return SysCountries
     * @date 2020/08/28
     * @author longli
     */
    public static function getByCode($code = '')
    {
        $code = trim($code);
        $field = strlen($code) == 2 ? 'code_two' : 'code_three';
        return static::get([$field => $code]);
    }

    /**
     * 获取所有的币种
     * @return array
     * @date 2021/03/06
     * @author longli
     */
    public static function getCurrencyAll()
    {
        return static::order('sort desc')
            ->where([
                ['currency_code', 'neq', ''],
                ['currency_name', 'neq', ''],
            ])
            ->group('currency_code')
            ->column('currency_name', 'currency_code');
    }

    /**
     * 通过货币代码获取一条数据
     * @param string $code 货币代码
     * @return SysCountries
     * @date 2020/08/28
     * @author longli
     */
    public static function getByCurrencyCode($code = '')
    {
        return static::get(["currency_code" => trim($code)]);
    }

    /**
     * 通过名称获取一条数据
     * @param string $name 国家英文或者中文名称
     * @return SysCountries
     * @date 2020/08/28
     * @author longli
     */
    public static function getByName($name = '')
    {
        $name = trim($name);
        $field = preg_match('/^[a-z]+$/i', $name)
            ? "name_en"
            : "name_ch";
        return static::get([$field => $name]);
    }

    /**
     * 获取国家 税率
     * @param string $code 国家二字码或三字码
     * @return float
     * @date 2020/12/12
     * @author longli
     */
    public static function getTaxRate($code = '')
    {
        if($rate = SysCountries::where("code_two", $code)
                ->whereOr("code_three", $code)
                ->value("tax_rate")
        ) return floatval($rate);
        return 0;
    }

    /**
     * 获取国家二字码和中文名称
     * @return SysCountries[]
     * @date 2020/12/13
     * @author longli
     */
    public static function getCodeNameCh()
    {
        return static::field(["country_id", "code_two", "name_ch"])
            ->where("name_ch", "neq", "")
            ->order("sort desc, name_ch")
            ->select();
    }

    /**
     * 通过二字码获取国家中文名称
     * @param int $code_two 国家二字码
     * @return string
     */
    public static function getNameByCodeTwo($codeTwo)
    {
        $codeTwo = trim($codeTwo);
        $sysCountry = static::get(['code_two' => $codeTwo]);
        return !empty($sysCountry) ? $sysCountry->name_ch : '';
    }
}
